<template>
  <ga-modal
    v-model:visible="visible"
    title-align="start"
    :width="600"
    @close="handleCancel(formRef)"
  >
    <template #title>{{ curId ? "编辑字典类型" : "创建字典类型" }}</template>
    <ga-spin style="width: 100%" :loading="loading">
      <ga-form ref="formRef" :model="formData">
        <ga-form-item
          field="dictName"
          label="名称"
          label-col-flex="50px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-input v-model="formData.dictName" placeholder="请输入名称" />
        </ga-form-item>
        <ga-form-item
          field="dictType"
          label="类型"
          label-col-flex="50px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-input v-model="formData.dictType" placeholder="请输入类型" />
        </ga-form-item>
        <!-- <ga-form-item
          field="required"
          label="是否启用"
          label-col-flex="50px"
          :rules="[RULE.NOT_NULL]"
          :validate-trigger="['change', 'input']"
        >
          <ga-switch size="mini" v-model="formData.required" />
        </ga-form-item> -->
        <ga-form-item field="remark" label="备注" label-col-flex="50px">
          <ga-textarea v-model="formData.remark" placeholder="请输入内容" />
        </ga-form-item>
      </ga-form>
    </ga-spin>
    <template #footer>
      <ga-button @click="visible = false">取消</ga-button>
      <ga-button type="primary" @click="handleOk">确定</ga-button>
    </template>
  </ga-modal>
</template>

<script setup>
import { ref, defineEmits, reactive } from "vue";
// import { editDictType, createDictType } from "@/api/tagMgmt.ts";
import { createDictType, editDictType } from "@/api/dataDictionary";
import { Message } from "@garco-design/web-vue";
import { RULE } from "@/constant/validators";
import useLoading from "@/hooks/loading";

const { loading, setLoading } = useLoading(false);
const formRef = ref(null);
const formData = reactive({
  dictName: "",
  dictType: "",
  remark: "",
});

const visible = ref(false);
const curId = ref("");
const open = async (record) => {
  visible.value = true;
  if (record && record?.dictId) {
    setLoading(true);
    curId.value = record.dictId;
    Object.keys(formData).forEach((item) => {
      formData[item] = record[item];
    });
    setLoading(false);
  }
};
// 保存
const emits = defineEmits(["fetchData"]);
const handleOk = async () => {
  const res = await formRef.value?.validate();
  if (!res) {
    try {
      const { code } = !curId.value
        ? await createDictType(formData)
        : await editDictType(curId.value, formData);
      if (code === 20000) Message.success("操作成功");
      emits("fetchData");
    } finally {
      visible.value = false;
    }
  }
};

const handleCancel = (formEl) => {
  curId.value = "";
  formEl.resetFields();
};
defineExpose({ open });
</script>

<style lang="scss" scoped></style>
